package com.hellohoper.script.config.engine.engine;

import com.hellohoper.script.config.engine.container.EngineContainer;
import com.hellohoper.script.config.engine.container.ScriptContainer;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by hk on 17/8/15.
 */
@Getter
@Setter
public class GroovyEngineService implements EngineService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GroovyEngineService.class);

    private ScriptEngineManager scriptEngineManager = new ScriptEngineManager();

    private ScriptContainer scriptContainer;

    private EngineContainer engineContainer;

    @Override
    public ScriptEngine getGroovyEngine(String appName, String ruleType) throws Exception {
        // 本地缓存中获得执行引擎
        ScriptEngine engine = engineContainer.getEngine(appName, ruleType);
        if (engine != null) {
            return engine;
        }
        // 脚本
        String script = scriptContainer.getScript(appName, ruleType);
        // 构建此脚本对应执行引擎
        engine = this.registerScript(script);
        // 添加到引擎容器
        engineContainer.addEngine(appName, ruleType, engine);
        return engine;
    }

    private ScriptEngine registerScript(String script) throws Exception {
        // 获得Groovy执行引擎
        ScriptEngine engine = this.scriptEngineManager.getEngineByName("groovy");
        // 添加脚本
        engine.eval(script);
        // 添加全局脚本
        this.registerGlobeScript(engine);

        return engine;
    }

    private void registerGlobeScript(ScriptEngine engine) throws Exception {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;

        try {
            inputStream = this.getClass().getResourceAsStream("/groovy/global.groovy");
            inputStreamReader = new InputStreamReader(inputStream);
            engine.eval(inputStreamReader);
        } catch (Exception e) {
            LOGGER.error("registerGlobeScriptFromJar Exception", e);
            throw e;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

        }

    }

}
